import * as types from '../types';
import axios from 'axios';
import { findIndex } from 'lodash';

export default {
  state: {
    data: []
  },
  mutations: {
    [types.SET_RULES]: (state, payload) => {
      state.data = [];
      for (let i = 0; i != payload.length; ++i) {
        state.data.push(payload[i]);
      }
    },
    [types.RESET_APPS]: (state) => {
      state.data = [];
    },
    [types.REMOVE_RULE]: (state, ruleid) => {
      let idx = findIndex(state.data, item => item.ruleid === ruleid);
      if (idx === -1) {
        console.error('cannot found ruleid??' + ruleid);
        return;
      }
      state.data.splice(idx, 1);
    }
  },
  actions: {
    load_rules: ({ commit }, payload) => {
      axios.get('/rules/').then(response => {
        commit(types.SET_RULES, response.data);
      }).catch(err => {
        console.log('error occured.');
        console.log(err);
      });
    },
    remove_rule: ({ commit }, ruleid) => {
      axios.delete("/rules/" + ruleid + "/").then(response => {
        commit(types.REMOVE_RULE, ruleid);
      }).catch(err => {
        console.log('remove rule failed.');
        console.error(err);
      });
    }
  }
}